package org.kjtc.controller;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kjtc.entity.*;
import org.kjtc.service.WeChartService;
import org.kjtc.weChatUtil.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@ResponseBody
public class MenuController {

    private static Logger logger = Logger.getLogger(MenuController.class);
    @Autowired
    private WeChartService weChartService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取公众号菜单栏
     * @return
     */
    @RequestMapping(value = "/searchWechatMenu")
    public Map<String, Object> searchWechatMenu() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<WechatMenu> menulist = null;
        try {
            menulist = weChartService.searchWeChatMenu();
            map.put("menuList", menulist);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("menuList", "Error");
            return map;
        }
        return map;
    }

    @RequestMapping(value = "/saveWechatMenu")
    public Map<String, Object> saveWechatMenu(WechatMenu wechatMenu) {
        Map<String, Object> map = new HashMap<String, Object>();
        wechatMenu.setCreateUser("weChat");
        wechatMenu.setUpdateUser("weChat");
        try {
            weChartService.insertWeChatMenu(wechatMenu);
            if (!"".equals(wechatMenu.getChangeMenuID())){
                weChartService.updateOrderNumber(wechatMenu);
            }
            map.put("result", "Success");
        }  catch (DuplicateKeyException ex) {
            String[] error = ex.getCause().getMessage().split("'");
            if ("MenuName".equals(error[3].trim())) {
                map.put("result", "MenuNameExist");
            } else {
                map.put("result", "DuplicateError");
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", "Error");
            return map;
        }
        return map;
    }

    @RequestMapping(value = "/updateWechatMenu")
    public Map<String, Object> updateWechatMenu(WechatMenu wechatMenu) {
        Map<String, Object> map = new HashMap<String, Object>();
        wechatMenu.setUpdateUser("weChat");
        try {
            weChartService.updateWeChatMenu(wechatMenu);
            if (!"".equals(wechatMenu.getChangeMenuID())) {
                weChartService.updateMoveMenuSure(wechatMenu);
            }
            map.put("result", "Success");
        } catch (DuplicateKeyException ex) {
            String[] error = ex.getCause().getMessage().split("'");
            if ("MenuName".equals(error[3].trim())) {
                map.put("result", "MenuNameExist");
            } else {
                map.put("result", "DuplicateError");
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", "Error");
            return map;
        }
        return map;
    }

    @RequestMapping(value = "/deleteWechatMenu")
    public Object deleteWechatMenu(WechatMenu wechatMenu) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if ("button".equals(wechatMenu.getLevel())) {
                wechatMenu.setParentMenuID(wechatMenu.getMenuID());
            }
            weChartService.deleteWeChatMenu(wechatMenu);
        } catch (Exception e) {
            e.printStackTrace();
            return map;
        }
        map.put("result", "Success");
        return map;
    }

    @RequestMapping(value = "/searchChangeMenuID")
    public Map<String, Object> searchChangeMenuID(WechatMenu wechatMenu) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<WechatMenu> changeIDList = null;
        try {
            changeIDList = weChartService.searchChangeMenuID(wechatMenu);
        } catch (Exception e) {
            e.printStackTrace();
            return map;
        }
        map.put("changeIDList", changeIDList);
        return map;
    }

    @RequestMapping(value = "/searchParentMenuID")
    public Map<String, Object> searchParentMenuID(WechatMenu wechatMenu) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<WechatMenu> parentIDList = null;
        try {
            parentIDList = weChartService.searchParentMenuID(wechatMenu);
        } catch (Exception e) {
            e.printStackTrace();
            return map;
        }
        map.put("parentIDList", parentIDList);
        return map;
    }

    @RequestMapping(value = "/saveMenu")
    public Map<String, Object> saveMenuSure(WechatMenu wechatMenu) {
        Map<String, Object> map = new HashMap<String, Object>();
        wechatMenu.setCreateUser("weChat");
        wechatMenu.setUpdateUser("weChat");
        try {
            weChartService.saveMenuSure(wechatMenu);
        } catch (DuplicateKeyException ex) {
            ex.printStackTrace();
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return map;
        }
        map.put("result", "Success");
        return map;
    }

    @RequestMapping(value = "/moveMenu")
    public Map<String, Object> moveMenuSure(WechatMenu wechatMenu) {
        Map<String, Object> map = new HashMap<String, Object>();
        wechatMenu.setUpdateUser("weChat");
        try {
            weChartService.updateMoveMenu(wechatMenu);
            if (!"".equals(wechatMenu.getChangeMenuID())) {
                weChartService.updateMoveMenuSure(wechatMenu);
            }
        } catch (DuplicateKeyException ex) {
            ex.printStackTrace();
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return map;
        }
        map.put("result", "Success");
        return map;
    }

    @RequestMapping(value = "/updateMenu")
    public Map<String, Object> updateMenuSure(WechatMenu wechatMenu) {
        Map<String, Object> map = new HashMap<String, Object>();
        wechatMenu.setUpdateUser("weChat");
        try {
            weChartService.updateMenuSure(wechatMenu);
        } catch (DuplicateKeyException ex) {
            ex.printStackTrace();
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return map;
        }
        map.put("result", "Success");
        return map;
    }

    @RequestMapping(value = "/publishMenu")
    public Map<String, Object> publishMenu() {

        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject menuJson = null;
        try {
            List<WechatMenu> wechatMenus = weChartService.getWechatMenuAllLevel();
            int menuCount = wechatMenus.size();
            if (menuCount > 0) {
                JSONArray buttonArray = new JSONArray();
                JSONObject buttonJson = null;
                JSONArray sub_buttonArray = null;
                JSONObject sub_buttonJson = null;
                for (WechatMenu wechatFirstMenu : wechatMenus) {
                    if (wechatFirstMenu.getParentMenuID() == 0) {
                        buttonJson = new JSONObject();
                        /*一级*/
                        buttonJson.put("type", wechatFirstMenu.getType());
                        buttonJson.put("name" , wechatFirstMenu.getMenuName());
                        buttonJson.put("key", wechatFirstMenu.getMenuKey());
                        if (!StringUtils.isEmpty(wechatFirstMenu.getUrl())) {
                            buttonJson.put("url",  wechatFirstMenu.getUrl());
                        }
                        if (!StringUtils.isEmpty(wechatFirstMenu.getAppID())) {
                            sub_buttonJson.put("appid", wechatFirstMenu.getAppID());
                        }
                        if (!StringUtils.isEmpty(wechatFirstMenu.getPagePath())) {
                            sub_buttonJson.put("pagepath", wechatFirstMenu.getPagePath());
                        }
                        sub_buttonArray = new JSONArray();
                        for (WechatMenu wechatSecondMenu : wechatMenus) {
                            if (wechatSecondMenu.getParentMenuID() != 0 && wechatSecondMenu.getParentMenuID() == wechatFirstMenu.getMenuID() && wechatSecondMenu.isEnabled()) {
                                /*二级*/
                                sub_buttonJson = new JSONObject();
                                sub_buttonJson.put("type", wechatSecondMenu.getType());
                                sub_buttonJson.put("name", wechatSecondMenu.getMenuName());
                                sub_buttonJson.put("url", wechatSecondMenu.getUrl());
                                sub_buttonJson.put("key", wechatSecondMenu.getMenuKey());
                                if (!StringUtils.isEmpty(wechatSecondMenu.getAppID())) {
                                    sub_buttonJson.put("appid", wechatSecondMenu.getAppID());
                                }
                                if (!StringUtils.isEmpty(wechatSecondMenu.getPagePath())) {
                                    sub_buttonJson.put("pagepath", wechatSecondMenu.getPagePath());
                                }
                                sub_buttonArray.add(sub_buttonJson);
                            }
                        }
                        if (!sub_buttonArray.isEmpty() && sub_buttonArray.size() > 0) {
                            buttonJson.put("sub_button", sub_buttonArray);
                        }
                        buttonArray.add(buttonJson);
                    } else {
                        break;
                    }
                }
                if (buttonArray.size() > 0) {
                    menuJson = new JSONObject();
                    menuJson.put("button", buttonArray);
                }
                buttonArray = null;
                buttonJson = null;
                sub_buttonArray = null;
                sub_buttonJson = null;
            } else {
                menuJson = null;
                map.put("result", "NotFound");
                logger.error("无可发布的菜单");
                return map;
            }
            if (menuJson != null && !menuJson.isNullObject() && !menuJson.isEmpty()) {
                String token = CommonUtil.getToken(CommonUtil.appid, CommonUtil.appsecret, redisTemplate);
                if (StringUtils.isEmpty(token)) {
                    map.put("result", "TokenError");
                    logger.error("获取微信(token)失败");
                } else {
                    int errorCode = CommonUtil.createMenu(menuJson.toString(), token);
                    if (errorCode == 0) {
                        map.put("result", "Success");
                    } else {
                        redisTemplate.delete(CommonUtil.Redis_WeChat_AccessToken);
                        map.put("result", "Failed");
                    }
                }
            } else {
                map.put("result", "NotFound");
                logger.error("无可发布一级菜单");
            }
            menuJson = null;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", "Error");
            logger.error("发布菜单异常：" + e.getMessage());
        }
        return map;
    }



}
